package open.tech.dawn.web.core.controller;

import lombok.extern.slf4j.Slf4j;
import open.tech.dawn.web.core.service.IAuthService;
import open.tech.dawn.web.core.support.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
public class LoginController extends BaseController {

    @Resource
    private IAuthService authService;

    /**
     * 更新token
     *
     * @return 返回
     */
    @GetMapping("/oauth/token")
    public Object updateToken() {
        try {
            return Result.createSuccess("oauth token", authService.updateToken());
        } catch (Exception e) {
            return Result.createError(e.getMessage());
        }
    }

    /**
     * 登录系统
     *
     * @param request 请求
     * @param response 响应
     * @return 返回
     */
    @PostMapping("login")
    public Object login(HttpServletRequest request, HttpServletResponse response) {
        try {
            return Result.createSuccess("登录成功", authService.login(request, response));
        } catch (Exception e) {
            return Result.createError(e.getMessage());
        }
    }

    @GetMapping("logout")
    public Object logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            authService.logout(authService.getUser(), request, response);
            return Result.createSuccess();
        } catch (Exception e) {
            log.error("退出失败", e);
            return Result.createError(e.getMessage());
        }
    }

}
